package com.zhengqing.system.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.Authenticator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.net.ssl.*;
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName HttpUtil
 * @Description TODO
 * @Author Des1gn
 * @Date 2021/11/23 16:21
 * @Version 1.0
 **/
@Slf4j
public class HttpUtil {


    private static Map<String,String> initHeader = new HashMap<>();

    private static List<OkHttpClient> clientList = new ArrayList<>();

    private static  OkHttpClient client = null ;

    static {
        client = new OkHttpClient().newBuilder()
                .proxy(new Proxy(Proxy.Type.HTTP,new InetSocketAddress("127.0.0.1",1080)))
                .callTimeout(240, TimeUnit.SECONDS)
                .connectTimeout(240,TimeUnit.SECONDS)
                .readTimeout(240,TimeUnit.SECONDS)
                .build();

        initHeader.put("content-type","application/json");
        initHeader.put("Referer","https://servicewechat.com/wx2c7f0f3c30d99445/91/page-frame.html");
        initHeader.put("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat");
        initHeader.put("zftsl","7d342b9ba70af48142f4943865c1cfd7");
        initHeader.put("host","cloud.cn2030.com");
        initHeader.put("Accept","*/*");
        initHeader.put("Accept-Encoding","gzip, deflate, br");
        initHeader.put("Connection","keep-alive");
    }

    private static OkHttpClient getClient(){
        return client;
    }

    public static JSONObject get(String url,String sessionId){
        HttpRequest get = cn.hutool.http.HttpUtil.createGet(url);
        get.setReadTimeout(10000);
        get.setConnectionTimeout(10000);
        get.addHeaders(initHeader);
        get.cookie("ASP.NET_SessionId="+sessionId+"; path=/");
        HttpResponse execute = get.execute();
        if (execute.getStatus() == 200){
            return JSONObject.parseObject(execute.body());
        }
        log.error("http请求错误,{}",execute);
        return null;
    }

    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    //检查客户端证书，若不信任该证书抛出异常，咱们自己就是客户端不用检查
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }
                    //检查服务器的证书，若不信任该证书抛出异常，可以不检查默认都信任
                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }
                    //返回受信任的X509证书数组
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }

    public static JSONObject getCookie(String url,String sessionId){
        HttpRequest get = cn.hutool.http.HttpUtil.createGet(url);
        get.addHeaders(initHeader);
        get.cookie("ASP.NET_SessionId="+sessionId+"; path=/");
        HttpResponse execute = get.execute();
        if (execute.getStatus() == 200){
            JSONObject result = JSONObject.parseObject(execute.body());
            String cookieStr = execute.getCookieStr();
            String substring = cookieStr.substring(cookieStr.indexOf("=")+1, cookieStr.indexOf(";"));
            System.out.println(substring);
            result.put("cookie",substring);
            return result;
        }
        log.error("http请求错误,{}",execute);
        return null;
    }

    public static JSONObject getJdk(String url,String sessionId){
        String result = null;
        try {
            HttpURLConnection urlConnection = (HttpURLConnection)new URL(url).openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("content-type","application/json");
            urlConnection.setRequestProperty("Referer","https://servicewechat.com/wx2c7f0f3c30d99445/91/page-frame.html");
            urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat");
            urlConnection.setRequestProperty("zftsl","84b8d26942b1b03d41269886ee7d924c");
            urlConnection.setRequestProperty("host","cloud.cn2030.com");
            urlConnection.setRequestProperty("Accept","*/*");
            urlConnection.setRequestProperty("Accept-Encoding","gzip, deflate, br");
            urlConnection.setRequestProperty("Connection","keep-alive");
            urlConnection.setRequestProperty("Cookie","ASP.NET_SessionId="+sessionId+"; path=/");
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 200) {
                InputStream is = urlConnection.getInputStream();
                // 封装输入流is，并指定字符集
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                }
                result = sbf.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (result != null){
            return JSONObject.parseObject(result);
        }
        return null;
    }

    public static String postJdk(String url,String body){
        String result = null;
        try {
            HttpURLConnection urlConnection = (HttpURLConnection)new URL(url).openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("content-type","application/json");
            urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat");
            urlConnection.setRequestProperty("Connection", "keep-alive");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(body.getBytes(StandardCharsets.UTF_8));
            if (urlConnection.getResponseCode() == 200) {
                InputStream is = urlConnection.getInputStream();
                // 封装输入流is，并指定字符集
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                }
                result = sbf.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (result != null){
            return result;
        }
        return null;
    }


    public static byte[] getOkHttp(String url){
        OkHttpClient client = getClient();
        byte[] result = null;
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .build();
        try {
            Response response = client.newCall(request).execute();
            result = response.body().bytes();
            if(result.length == 0){
                log.error("获取pdf数据失败->{}",url);
            }
            response.close();
        } catch (IOException e) {
            log.error("获取pdf数据失败->{}->{}",url,e);
        }
        return result;
    }


    public static String postOkHttp(String url,String body){
        OkHttpClient client = getClient();
        String result = null;

        Request request = new Request.Builder()
                .url(url)
                .method("POST", RequestBody.create(body,MediaType.parse("application/json")))
                .header("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            result = response.body().string();
            response.close();
        } catch (IOException e) {
            log.error("post请求失败->{}->{}",url,e);
        }
        return result;
    }

    public static String postHutool(String url,String body){
        HttpRequest post = cn.hutool.http.HttpUtil.createPost(url);
//        Map<String,String> headMap = new HashMap<>();
//        headMap.put("Accept","*/*");
//        headMap.put("Accept-Encoding","gzip, deflate, br");
//        headMap.put("Connection","keep-alive");
//        headMap.put("Content-Type","application/json");
//        post = post.headerMap(headMap,true);
        post = post.body(body);
        post = post.setSSLSocketFactory(getSSLSocketFactory());
        return post.execute().body();
    }

    public static byte[] getHutool(String url){
        HttpRequest get = cn.hutool.http.HttpUtil.createGet(url);
        return get.execute().bodyBytes();
    }

//    public static String getOkHttpStr(String url,String sessionId,Proxy proxy){
//        OkHttpClient client = getClient(proxy);
//        String result = null;
//        Request request = new Request.Builder()
//                .url(url)
//                .method("GET", null)
//                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat")
//                .addHeader("content-type", "application/json")
//                .addHeader("Referer", "https://servicewechat.com/wx2c7f0f3c30d99445/91/page-frame.html")
//                .addHeader("zftsl", "84b8d26942b1b03d41269886ee7d924c")
//                .addHeader("Cookie", "ASP.NET_SessionId="+sessionId+"; path=/")
//                .build();
//        try {
//            Response response = client.newCall(request).execute();
//            result = response.body().string();
//            log.info("http request : {} , response : {}, proxy:{}",url,result,client.proxy()!=null?client.proxy().toString():null);
//            if(StringUtils.isEmpty(result) || result.indexOf("访问异常") > -1){
//                return null;
//            }
//            return result;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    public static JSONObject getOkHttpMiao(String url,String sessionId,Proxy proxy){
//        OkHttpClient client = getClient(proxy);
//        String result = null;
//        Request request = new Request.Builder()
//                .url(url)
//                .method("GET", null)
//                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat")
//                .addHeader("content-type", "application/json")
//                .addHeader("tk", sessionId)
//                .build();
//        try {
//            Response response = client.newCall(request).execute();
//            result = response.body().string();
//            log.info("http request : {} , response : {}, proxy:{}",url,result,client.proxy()!=null?client.proxy().toString():null);
//            if(StringUtils.isEmpty(result) || result.indexOf("访问异常") > -1){
//                return null;
//            }
//            JSONObject jsonObject = JSONObject.parseObject(result);
//            return jsonObject;
//        } catch (IOException e) {
//        }
//        return null;
//    }
//
//    public static JSONObject getOkHttpMiaoSubmit(String url,String sessionId,String sign,Proxy proxy){
//        OkHttpClient client = getClient(proxy);
//        String result = null;
//        Request request = new Request.Builder()
//                .url(url)
//                .method("GET", null)
//                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat")
//                .addHeader("content-type", "application/json")
//                .addHeader("tk", sessionId)
//                .addHeader("ecc-hs", sign)
//                .build();
//        try {
//            Response response = client.newCall(request).execute();
//            result = response.body().string();
//            log.info("http request : {} , response : {}, proxy:{}",url,result,client.proxy()!=null?client.proxy().toString():null);
//            if(StringUtils.isEmpty(result) || result.indexOf("访问异常") > -1){
//                System.out.println("请求失败---"+result);
//                return null;
//            }
//            System.out.println("请求成功---"+result+client.proxy().toString());
//            JSONObject jsonObject = JSONObject.parseObject(result);
//            return jsonObject;
//        } catch (IOException e) {
//        }
//        return null;
//    }
//
//
//    public static String getStr(String url,String sessionId){
//        HttpRequest get = cn.hutool.http.HttpUtil.createGet(url);
//        get.addHeaders(initHeader);
//        get.cookie("ASP.NET_SessionId="+sessionId);
//        HttpResponse execute = get.execute();
//        if (execute.getStatus() == 200){
//            return execute.body();
//        }
//        log.error("http请求错误,{}",execute);
//        return null;
//    }


}
